<?php
/**
 * Load the configurations per module
 * Module configurations is defined in module.ini under configs folder of each module
 *
 * @category   Custom
 * @package    Custom_Controller
 * @subpackage Plugin
 * @link http://lenss.nl/2010/02/zend-framework-bootstrapping-modules/
 * @since $Id:$
 */
class Custom_Controller_Plugin_ModuleLoader extends Zend_Controller_Plugin_Abstract
{
    /** @var array contains all module names */
    protected $_modules;

    /**
     * Plug-in Construtor
     * 
     * @param array $modulesList
     */
    public function __construct(array $modulesList)
    {
        $this->_modules = $modulesList;
    }
    
	/**
     * Called before Zend_Controller_Front enters its dispatch loop.
     *
     * @param  Zend_Controller_Request_Abstract $request
     * @return void
     * @throws Custom_Exception
     */
    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        $module = $request->getModuleName();

        if (!isset($this->_modules[$module])) {
            throw new Custom_Exception("Module does not exist!");
        }

        $bootstrapPath = $this->_modules[$module];

        $bootstrapFile = realpath(dirname($bootstrapPath) . '/Bootstrap.php');
        if (NULL == $bootstrapFile) {
            throw new Custom_Exception("Module Boostrap file does not exist!");
        }
        
        $iniFile = realpath(APPLICATION_PATH . '/modules/' . $module . '/configs/module.ini');       
        $class         = ucfirst($module) . '_Bootstrap';
        $application   = new Zend_Application(
            APPLICATION_ENV,
            $iniFile
        );        
        
        if (Zend_Loader::loadFile('Bootstrap.php', dirname($bootstrapPath))
            && class_exists($class)) {
            $bootstrap = new $class($application);
            $bootstrap->bootstrap();
        }
    }
}